#include <QpwNetwork.h>
#include <QpwPackages.h>
#include <QyMath.h>
#include "QpwPlayerController.h"
#include "QpwRenderItems.h"

QpwPlayerController::QpwPlayerController( QyGL::Scene * target ) : QyGL::InputController(target),
    client(0),
    p_moving(false)
{
}

void QpwPlayerController::mousePressd( const QyGL::MouseEvent & event ) {

    if (!client)
        return;

}

void QpwPlayerController::mouseMoved( const QyGL::MouseEvent & event ) {

    if ( !client || !player )
        return;

    qreal direction = QyMath::radian( player->position.zDirection( event.glPos() ) );

    client->send( &QpwPackages::PlayerControl::changeDirection(direction) );

}

void QpwPlayerController::mouseReleased( const QyGL::MouseEvent & event ) {

    if (!client)
        return;

}

void QpwPlayerController::keyPressd( QKeyEvent * event ) {

    if (!client)
        return;

//     qreal movingDirection = 0.0;
    int key = event->key();

    switch (key) {

    case Qt::Key_W:
        if ( lastKey != key )
            client->send( &QpwPackages::PlayerControl::beginMoving(0) );
        lastKey = key;
        keys ++;
        p_moving = true;
        break;

    case Qt::Key_S:
        if ( lastKey != key )
            client->send( &QpwPackages::PlayerControl::beginMoving(M_PI) );
        lastKey = key;
        keys ++;
        p_moving = true;
        break;

    case Qt::Key_A:
        if ( lastKey != key )
            client->send( &QpwPackages::PlayerControl::beginMoving(-M_PI/2.0) );
        lastKey = key;
        keys ++;
        p_moving = true;
        break;

    case Qt::Key_D:
        if ( lastKey != key )
            client->send( &QpwPackages::PlayerControl::beginMoving(M_PI/2.0) );
        lastKey = key;
        keys ++;
        p_moving = true;
        break;

    }

}

void QpwPlayerController::keyReleased( QKeyEvent * event ) {

    if (!client)
        return;

    switch ( event->key() ) {

    case Qt::Key_W:
    case Qt::Key_A:
    case Qt::Key_S:
    case Qt::Key_D:
        if (!--keys) {
            p_moving = false;
            client->send( &QpwPackages::PlayerControl::endMoving() );
            lastKey = 0;
        }
        break;

//     case Qt::Key_A:
//         break;

//     case Qt::Key_S:
//         break;

//     case Qt::Key_D:
//         break;

    }

}
